import { useCallback, useEffect, useRef, useState } from 'react'
import Utils from './../utils/util'

// setState 回调函数无法拿到最新state
const useSetState = (initState) => {
    const [state, setState] = useState(initState)
    let isUpdate = useRef()
    const setXState = useCallback((_state, cb) => {
        setState(prev => {
            isUpdate.current = cb
            return Utils.isFunction(_state) ? _state(prev) : { ...prev, ..._state }
        })
    }, [])
    useEffect(() => {
        isUpdate.current && Utils.isFunction(isUpdate.current) && isUpdate.current()
    }, [state])

    return [state, setXState]
}

export default useSetState